package org.as3search.properties {
	/*
	 * as3search - http://code.google.com/p/as3search
	 * Copyright (c) 2009-2010 by respective authors. All rights reserved.
	 *
	 * This library is free software; you can redistribute it and/or modify it under the
	 * terms of the GNU Lesser General Public License as published by the Free Software
	 * Foundation; either version 2.1 of the License, or (at your option) any later
	 * version.
	 *
	 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
	 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
	 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
	 *
	 * You should have received a copy of the GNU Lesser General Public License along
	 * with this library; if not, write to the Free Software Foundation, Inc.,
	 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
	 */
	
	/**
	 * <code>DefaultPropertyResolver</code> is the default property
	 * resolver for as3search. It currently supports simple dot-notation
	 * property resolution, but in future versions of the library, it will
	 * be able to resolve method results and XML properties.
	 * 
	 * @see org.as3search.properties.PropertyResolver
	 */
	public class DefaultPropertyResolver implements PropertyResolver {
		/**
		 * Creates a new <code>DefaultPropertyResolver</code> instance. 
		 */
		public function DefaultPropertyResolver() {
			
		}
		/**
		 * @inheritDoc
		 */
		public function resolveProperty(propertyName:String, target:Object):Object {
//			check if it's a valid property name
			if (propertyName == null || !(new RegExp("^\\w[\\w\\.]*\\w$").test(propertyName)))
				throw new ArgumentError("'" + propertyName + "' is not a valid property name.");
//			if it's null, just get outta here.
			if (target == null)
				return null;
//			now do the complex property resolution
			var properties:Array = propertyName.split(".");
			var currentObject:Object = target;
			while (properties.length > 0) {
				var currentProperty:String = String(properties.shift());
				if (!currentObject.hasOwnProperty(currentProperty))
					throw new ArgumentError("Target does not have a property named '" + propertyName + "'");
				
				currentObject = currentObject[currentProperty];
				
				if (currentObject == null)
					break;
			}				
			
			return currentObject;
		}
	}
}